package top.marandi.controller;

import ch.qos.logback.core.util.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.marandi.Service.UserService;
import top.marandi.pojo.Users;
import top.marandi.pojo.bo.UsersBO;
import top.marandi.pojo.vo.UsersVO;
import top.marandi.utils.FastDFSClient;
import top.marandi.utils.FileUtils;
import top.marandi.utils.IMoocJSONResult;
import top.marandi.utils.MD5Utils;

@RestController
@RequestMapping("u")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FastDFSClient fastDFSClient;

    @PostMapping("/registerOrLogin")
    public IMoocJSONResult registerOrLogin(@RequestBody Users user) throws Exception {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名或密码不能为空");
        }
        boolean userExist = userService.hasUser(user.getUsername());
        Users userResult = null;
        if (userExist) {
            userResult = userService.login(user.getUsername(), MD5Utils.getMD5Str(user.getPassword()));
            if (userResult == null) {
                return IMoocJSONResult.errorMsg("用户名或密码不正确");
            }
        } else {
            user.setNickname(user.getUsername());
            user.setFaceImage("");
            user.setFaceImageBig("");
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            userResult = userService.save(user);
        }
        UsersVO uservo = new UsersVO(userResult);
        return IMoocJSONResult.ok(uservo);
    }

    @PostMapping("/uploadFaceBase64")
    public IMoocJSONResult uploadFaceBase64(@RequestBody UsersBO userBO) throws Exception {
        String base64Data = userBO.getFaceData();
        String userFacePath = "D:/"+userBO.getUserId()+"userface64.png";
        FileUtils.base64ToFile(userFacePath,base64Data);
//        上传文件到fastdfs
        MultipartFile multipartFile = FileUtils.fileToMultipart(userFacePath);
        String url = fastDFSClient.uploadBase64(multipartFile);
        System.out.println(url);
//    获取缩略图url
        String thump = "_80x80.";
        String thumpImageUrl = url.replaceAll("\\.",thump);
        Users user = new Users();
        user.setId(userBO.getUserId());
        user.setFaceImage(thumpImageUrl);
        user.setFaceImageBig(url);

        user = userService.updateUserInfo(user);


        return IMoocJSONResult.ok(user);
    }
}
